require 'yaml'
IRCBot::Plugin.define "conversationalist" do
	help_string "Annoys people to death. He'll bitch if you, for instance, abuse of Caps Lock."
	@timer = Time.new
	@timeout = 333
	@chan_timer = {}
	@random_stuff = YAML::load(File.open($config['global']['plugin_data_dir']+'/conversationalist.yml'))
	if @random_stuff.nil? then @random_stuff = ['HEY NIEXS, YOU NEED STUFF TO SAY HERE']; end
	@enabled = true
	# This thread will control the random stuff saying.
	def say_random_stuff(target)
		puts "Saying random stuff"
		privmsg(target,@random_stuff[rand(@random_stuff.count)].downcase.capitalize)
		@chan_timer[target] = Time.new
	end
	
	def privmsg_function(user,target,message,usermask)
		# Bucket-like stuff
		if message.strip =~ /^([\.\s]+)$/ and message.strip.length >= 3 then
			what_to_say = @random_stuff.sort_by{rand}[0].strip
			what_to_say[0] = '' if what_to_say[0].chr == '"'
			what_to_say[-1] = '' if what_to_say[-1].chr == '"'
			privmsg(target,what_to_say.strip.downcase.capitalize.gsub("~",user))
		end
		@chan_timer[target.downcase] = Time.new if target.start_with?('#')
		# Weird stuff
		if Time.new - @timer >= 20 and Time.new.to_i > @timeout then
			triggered = true
			if message == message.upcase and message.length > 30 then
				replies = ["NICE DRIVING, #{user.upcase}.","YOU CAN RESUME NORMAL DRIVING NOW.","WATCH OUT, YOU STILL NEED TO STEER","NICE CAPS MATE","IT'S TO THE LEFT OF YOUR 'A' KEY."]
				privmsg(target,replies[rand(replies.count)])
			elsif rand(512) == 5 then
				privmsg(target,"Bananas!")
			elsif message =~ /[!1]{4}/ then
				privmsg(target,"You must be real serious!")
			end
			if triggered then
				@timer = Time.new
				triggered = false
			end
		end
		if message.downcase.start_with?($config[$network]['nickname'].downcase) then
			message = message.downcase.sub($config[$network]['nickname'].downcase,"")
			message[0] = "" if message[0..0] != " "
			message = message.strip
			if message == 'shut up' then
				privmsg(target,"OK #{user}, be back in five minutes.")
				@timeout = Time.new.to_i + 300
			end
		end
	end
	def command(user,target,message,usermask)
		if get_plugin('auth').is_auth_user?(usermask) then
			if @enabled then
				@enabled = false
				privmsg(target,"Random stuff disabled.")
			else
				@enabled = true
				privmsg(target,"Random stuff enabled.")
				Thread.new do
					if @enabled then
						loop do
							for i in @chan_timer
#				puts "Tick..."
								if i[1] == nil or Time.new - i[1] >= 600 then
									puts "Running if..."
									say_random_stuff(i[0])
#									i[1] = Time.new
									puts "Saying stuff"
					
								end
							end
						end
					end
				end		
			end
		end
	end
end
